package fti.uksw.ruang;

import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import fti.uksw.ruang.model.Login;
import fti.uksw.ruang.model.MsgCode;
import fti.uksw.ruang.websocket.ClientListener;
import fti.uksw.ruang.websocket.WebSocketClient;

public class LoginActivity extends ActionBarActivity implements
		OnClickListener, ClientListener {

	private static String TAG = LoginActivity.class.getName();

	private Button btnLogin;
	private EditText etUsername;
	private EditText etPass;

	public static WebSocketClient wsClient = new WebSocketClient();

	private SharedPreferences prefs;
	private SharedPreferences prefLogin;

	public static final String PREF_IP_SERVER = "ip_server";
	public static final String PREF_PORT = "port";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		
//		prefLogin = getSharedPreferences(Login.TAG, Context.MODE_PRIVATE);
				
		btnLogin = (Button) findViewById(R.id.buttonLogin);
		etUsername = (EditText) findViewById(R.id.editTextUsername);
		etPass = (EditText) findViewById(R.id.editTextPassword);

		etUsername.requestFocus();
		etUsername.setText("yos");
		etPass.setText("yos");
		btnLogin.setOnClickListener(this);

		wsClient.addListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.show_setting, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == R.id.action_settings) {
			Intent intent = new Intent(this, ShowSettingActivity.class);
			startActivity(intent);
		}

		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return false;
	}

	private void sendNimAndPassword() {
		JSONObject obj = new JSONObject();
		try {
			obj.put(MsgCode.MSGCODE, MsgCode.LOGINREQ);
			obj.put(Login.USERNAME, etUsername.getText());
			obj.put(Login.PASSWORD, etPass.getText());
			wsClient.sendTextMessage(obj.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private boolean checkAuthLogin(String msg) {
		JSONObject aMsg;
		boolean ret = false;
		try {
			aMsg = new JSONObject(msg);
			if (aMsg.getString(MsgCode.LOGIN_AUTH).equals("true")) {
				ret = true;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public void onConnect(String message) {
		sendNimAndPassword();
	}

	@Override
	public void onMessage(String message) {
		Log.d(LoginActivity.class.getName(), message);

		try {
			JSONObject obj;
			obj = new JSONObject(message);

			String msgCode = obj.getString(MsgCode.MSGCODE);

			if (msgCode.equals(MsgCode.MSGCONFIRM)) {

				Toast.makeText(this, obj.getString(MsgCode.MSGCONTENT),
						Toast.LENGTH_SHORT).show();
			}
			if (msgCode.equals(MsgCode.LOGINRES)) {
				if (checkAuthLogin(message)) {

					Login l = new Login();
					JSONObject jsonLogin = obj.getJSONObject(Login.TAG);
					l.setUsername(jsonLogin.getString(Login.USERNAME));
					l.setPassword(jsonLogin.getString(Login.PASSWORD));
					l.setId(jsonLogin.getInt(Login.ID));
					l.setIdUser(jsonLogin.getInt(Login.IDUSER));
					l.setLastLogin(new Date(jsonLogin.getLong(Login.LASTLOGIN)));

					Intent i = new Intent(this, CalViewAct.class);
					i.putExtra(Login.TAG, l);
					startActivity(i);
					wsClient.removeListener(this);
					finish();
				} else {
					// JSONObject obj = new JSONObject(message);
					String warning = obj.getString(Login.TAG);
					Toast.makeText(this, warning, Toast.LENGTH_SHORT).show();
					wsClient.closeConnection();
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(byte[] data) {
		Log.d(TAG, "byte msg : " + data.toString());
	}

	@Override
	public void onDisconnect(String reason) {
		String aReason[] = reason.split(";");
		Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onError(Exception error) {

	}


	@Override
	public void onClick(View v) {
		if (v == btnLogin) {
			if (!wsClient.isConnected()) {
				String ipServ = prefs.getString(PREF_IP_SERVER, null);
				String port = prefs.getString(PREF_PORT, null);
				wsClient.setWsUri(ipServ, port);
				wsClient.startConnection();
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		wsClient.removeListener(this);
	}
}
